<template>
  <div>
    <ea-dialog
      v-bind="$attrs"
      v-on="$listeners"
      width="900px"
      ref="elDialog"
      :title="title"
      :type="type"
      class="dialog"
      :modal="false"
      @submit="submit"
      @closed="handleClosed"
      @reset="$refs.form.resetFields()"
    >
      <el-scrollbar wrap-class="scroll-wrap-y">
        <el-form
          ref="form"
          :rules="rules"
          :model="singleData"
          label-width="100px"
        >
          <el-form-item label="课件名称" prop="resourcename">
            <el-input
              v-model="singleData.resourcename"
              placeholder="请输入课件名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="选择科目" prop="subid">
            <el-select
              v-model="singleData.subid"
              clearable
              @clear="(singleData.chapterid = null) && (chapters = [])"
              @change="getChapter($event)"
              placeholder="请选择科目"
            >
              <el-option
                v-for="item in subjects"
                :key="item.subid"
                :label="item.subname"
                :value="item.subid"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="选择章节" prop="chapterid">
            <el-select v-model="singleData.chapterid" placeholder="请选择章节">
              <el-option
                v-for="item in chapters"
                :key="item.chapterid"
                :label="item.chaptername"
                :value="item.chapterid"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="排序号" prop="sort">
            <el-input
                v-model="singleData.sort"
                placeholder="请输入排序"
            ></el-input>
          </el-form-item>
          <el-form-item class="is-required" label="课件封面">
            <el-upload
              ref="uploadDiagram"
              action=""
              :class="{ hiddenUpload: hiddenUpload }"
              :auto-upload="false"
              :file-list="oldDiagram"
              :on-change="diagramChange"
              :on-remove="diagramRemove"
              list-type="picture-card"
            >
              <i class="el-icon-plus"></i>
              <div slot="tip" class="el-upload__tip">
                只能上传<b class="danger"> jpg / jpeg / png </b>文件，且不超过<b
                  class="danger"
                  >5MB</b
                >
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item
            class="is-required"
            label="课件视频"
          >
            <el-upload
              ref="uploadVideo"
              :auto-upload="false"
              :on-change="videoChange"
							:file-list="veidoList"
							:on-remove="veidoRemove"
							:limit="1"
              action=""
            >
              <el-button size="small" type="primary">选择视频</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传<b class="danger">mp4 / webm</b>文件，且不超过<b
                  class="danger"
                >
                  1024MB
                </b>
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item label="课件介绍">
            <editor
              ref="editor"
              v-loading="editorLoading"
              element-loading-text="加载富文本编辑器中..."
              :height="400"
              @ready="editorOnReady"
            />
          </el-form-item>
        </el-form>
      </el-scrollbar>
    </ea-dialog>
    <el-dialog
      title="上传文件进度"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showProgress"
    >
      视频上传进度：
      <el-progress
        v-show="fileList.video"
        :percentage="videoProgress"
        :format="formatProgress"
      />
      封面上传进度：
      <el-progress
        v-show="fileList.diagram"
        :percentage="diagramProgress"
        :format="formatProgress"
      />
    </el-dialog>
  </div>
</template>

<script>
import editAndAdd from "../../../mixins/business/editAndAdd";
//添加课件顺序 uploadVideo->uploadVideoSuccess->uploadDiagram->submit

export default {
  name: "EaCourseware",
  mixins: [editAndAdd],
  props: ["subjects"],
  data() {
    const dataStruct = {
      chapterid: null,
      reintroduction: "",
      resourcename: "",
      subid: null,
      resourceid: null,
      diagramUploaded: false,
      thumbnail: null,
      path: null
    };
    return {
      moduleName: "课件",
      dataStruct,
      singleData: this.deepClone(dataStruct),
      rules: {
        resourcename: { required: true, message: "请输入资源名称！" },
        subid: { required: true, message: "请选择科目！" },
        chapterid: { required: true, message: "请选择章节！" }
      },
      fileList: {
        video: null,
        diagram: null
      },
      oldDiagram: [],//图片
			veidoList:[],//视频
      showProgress: false,
      videoProgress: 0,
      diagramProgress: 0,
      chapters: [],
      editorLoading: false,
      hiddenUpload: false
    };
  },
  watch: {
    "singleData.reintroduction": {
      immediate: true,
      handler(n) {
        //set the initial value for the editor when editing
        if (this.type === "edit" && n.length && !this.editorLoading)
          this.$refs.editor.setContent(n);
      }
    },
    "singleData.resourcename":{
      handler(n){
        if(n=='' && this.singleData.subid==null && this.singleData.chapterid==null){
          this.singleData.reintroduction=''
          this.$nextTick(() => {
            this.$refs.editor.setContent(this.singleData.reintroduction);
          });
        }
      }
    },
    "singleData.subid":{
      handler(n){
        if(n==null && this.singleData.resourcename=='' && this.singleData.chapterid==null){
          this.singleData.reintroduction=''
          this.$nextTick(() => {
            this.$refs.editor.setContent(this.singleData.reintroduction);
          });
        }
      }
    },
    "singleData.chapterid":{
      handler(n){
        if(n==null && this.singleData.subid==null && this.singleData.resourcename==''){
          this.singleData.reintroduction=''
          this.$nextTick(() => {
            this.$refs.editor.setContent(this.singleData.reintroduction);
          });
        }
      }
    },
		"singleData.path":{
		  handler(n){
		    if(n){
		      this.veidoList.push({name:this.singleData.originalfilename,url:this.singleData.path})
		    }
		  }
		}
  },
  created() {
    this.editorLoading = true;
  },
  methods: {
    formatProgress(progress) {
      return progress === 100 ? "上传成功！" : progress + "%";
    },
    editorOnReady() {
      this.editorLoading = false;
      this.type === "edit" &&
        this.$refs.editor.setContent(this.singleData.reintroduction);
    },
    diagramChange(file) {
      const verify = this.verifyFile(file, "image", 5);
      if (verify !== true) {
        this.$message.error(verify);
        this.$refs.uploadDiagram.clearFiles();
        return;
      }
      this.fileList.diagram = file.raw;
      this.hiddenUpload = true;
    },
    videoChange(file) {
      const verify = this.verifyFile(file, "video", 1024);
      if (verify !== true) {
        this.$message.error(verify);
        this.$refs.uploadVideo.clearFiles();
      }
      this.fileList.video = file.raw;
    },
		veidoRemove(){
			this.hiddenUpload = false;
			this.veidoList=[];
		},
    diagramRemove() {
      this.hiddenUpload = false;
      this.oldDiagram = [];
    },
    getChapter(subId) {
      this.singleData.chapterid = null;
      subId &&
        this.api.getChapter(subId).then(res => {
          this.chapters = res;
        });
    },
    async handle() {
      const { fileList } = this;
      // if (this.singleData.reintroduction.length === 0) {
      //   this.noField("课件介绍不能为空！");
      //   return Promise.resolve({ ignore: true });
      // }
			
      if (!this.fileList.video && !this.veidoList.length) {
        this.$message.error("请选择课件视频！");
        return Promise.reject();
      }
      if (!this.fileList.diagram && !this.oldDiagram.length) {
        this.$message.error("请选择课件封面！");
        return Promise.reject();
      }
			
      this.showProgress = true;
			 let video, diagram;
      if (this.type === "add") {
        [video, diagram] = await Promise.all([
          this.uploadVideo(),
          this.uploadDiagram()
        ]);
				this.singleData.path = video.name;
				this.singleData.originalfilename = this.fileList.video.name
				this.singleData.thumbnail = diagram.name;
      } else{
        //编辑时path不传
        // this.singleData.path = null;
				 if(!this.veidoList.length || this.fileList.video){
					 video= await this.uploadVideo();
					 this.singleData.path = video.name;
					 this.singleData.originalfilename = this.fileList.video.name
					 // console.log(video.name,12212131231)
				 }else{
					 this.singleData.path = null;
				 }
				if(!this.oldDiagram.length || this.fileList.diagram){
						diagram=await this.uploadDiagram();
						this.singleData.thumbnail=diagram.name;
				}else{
					this.singleData.thumbnail = this.oldDiagram[0].url;
				}
      }
      if (!this.oldDiagram.length) {
        diagram = await this.uploadDiagram();
        this.singleData.thumbnail = diagram.name;
      }
      this.singleData.reintroduction = this.$refs.editor.getContent();
      //关闭上传进度弹窗
      this.showProgress = false;
      this.$nextTick(() => {
        this.videoProgress = this.diagramProgress = 0;
      });
      return this.axios.post("/sys/courseware/submitCourse", this.singleData);
    },
    uploadVideo() {
      return this.uploadFile("course", this.fileList.video, progress => {
        this.videoProgress = progress;
      });
    },
    uploadDiagram() {
      return this.uploadFile("course", this.fileList.diagram, progress => {
        this.diagramProgress = progress;
      });
    },
    handleClosed() {
      if (this.$refs.uploadVideo) {
        this.$refs.uploadVideo.clearFiles();
        this.$refs.uploadDiagram.clearFiles();
      }
			this.veidoRemove();
      this.diagramRemove();
      this.$refs.editor.setContent("");
      this.singleData = this.deepClone(this.dataStruct);
      this.fileList.diagram = this.fileList.video = null;
      this.end();
    }
  }
};
</script>

<style scoped>
.dialog {
  z-index: 1000 !important;
}

body >>> .v-modal {
  z-index: 999 !important;
}

.el-progress >>> .el-progress-bar {
  margin-right: -90px;
  padding-right: 90px;
}
</style>
